package protocol.JS_2017;

import utils.HexUtils;

import java.nio.charset.Charset;

public class JS_ATL_2017Cmd {

    private byte[] cmd;
    private int index = 8;

    public JS_ATL_2017Cmd(byte[] cmd){
        this.cmd = cmd;
    }

    public void resetIndex(){
        index = 8;
    }

    /**
     * 获取命令字
     * @return
     */
    public String readOrder(){
        return HexUtils.toHex(cmd[7],1);
    }

    public void moveIndex(int len){
        index += len;
    }

    public byte order(){
        return cmd[7];
    }

    public int readInt(int len){
        if (len > 4){
            //int类型最多占4个字节
            return -1;
        }
        int num = 0;
        for (int i= 0;i<len;i++){
            num = num << 8;
            num = num |(cmd[index+i] &0xFF);
        }
        index += len;
        return num;
    }

    public String readString(int len){
        return readString(len,Charset.forName("GBK"));
    }

    /**
     * 获取字符串
     * @param len 如果为-1，则持续读到0x00判定结束
     * @param charset
     * @return
     */
    public String readString(int len, Charset charset){

        if (len < 0){
            for (int i = 0;i< cmd.length;i++){
                if (cmd[index+i] == 0x00){
                    len = i+1;
                    break;
                }
            }
        }

        byte[] data = new byte[len];
        System.arraycopy(cmd,index,data,0,len);
        index += len;
        return new String(data,charset);
    }

    public String readBCD(int len){
        byte[] data = new byte[len];
        System.arraycopy(cmd,index,data,0,len);
        index+= len;
        return HexUtils.toHexStr(data);
    }

    /**
     * 剩余可读内容大小
     * @return
     */
    public int leftSize(){
        return cmd.length - 1 - index;
    }

    /**
     * 外设类型
     * @return
     */
    public byte device(){
        return cmd[6];
    }

    public String deviceStr(){
        int device = device();

        String deviceStr = "";

        switch (device){
            case 0x65:
                deviceStr = "DMS";
                break;
            case 0x64:
                deviceStr = "ADAS";
                break;
            default:
                deviceStr = "未知设备";
                break;
        }
        return "( "+HexUtils.toHex(device,1)+")"+deviceStr;
    }

    public int seq(){
        int seq = cmd[2] &0xFF<<8;
        return seq |(cmd[3] &0xFF);
    }
}
